package com.shop.model.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shop.model.entity.UserTb;
import com.shop.model.mapper.UserTbMapper;
import com.shop.model.service.IUserTbService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class MyRealm extends AuthorizingRealm {
    @Autowired
    private IUserTbService iUserTbService;

    /* 授权 */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //类似于当前用户的这个对象  角色权限信息需要从数据库查询
        String username = (String) principalCollection.getPrimaryPrincipal();
        //
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        QueryWrapper<UserTb> wrapper=new QueryWrapper<>();
        wrapper.eq("user_name", username);
        UserTb userTb = iUserTbService.getOne(wrapper);
        String userName = userTb.getUserName();
        if(userName.equals(username)){
            //simpleAuthorizationInfo.addStringPermission("user:update");
            //simpleAuthorizationInfo.addRole("admin");
        }else{
            //simpleAuthorizationInfo.addStringPermission("user:*");
            //simpleAuthorizationInfo.addRole("root");
        }
        return simpleAuthorizationInfo;
    }

//    认证

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //用户名
        String username = (String) token.getPrincipal();
//        System.out.println("电话号码=="+username);
        QueryWrapper<UserTb> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", username);
        //调用userSErvice中的方法查询该用户是否存在
        UserTb userTb = iUserTbService.getOne(wrapper);
        Integer userStatus = userTb.getUserStatus();
        if(userStatus==1){
            //        System.out.println(userTb);
            if (userTb == null) {
                throw new UnknownAccountException();
            }
            //验证登录名和密码 以及加密方式
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userTb.getUserName(), userTb.getPassword(),this.getName());
            return info;
        }
//        else{
//            System.out.println("该用户已经禁用！");
//            throw new AuthenticationException();
//        }
        return null;
    }
}
